# -*- coding:utf-8 -*-
import random
import time
from time import sleep

from munch import munchify

from PageClass import FscIndexPage, EcsMyApprovalPage
from PageClass import BoeCommon
from PageClass import AuditAdjustDirectorPage
from PageClass import MyAuditListPage
from TestCases.common._baseClass import _BaseClass
from TestCases.common.handleTimer import HandleTimer
from TestCases.common.loginDepend import LoginDepend
from Util import logger, config, ZTCCLOUDError


class SharingCenterApprove(_BaseClass):

    def __init__(self, boeNum, node='preliminaryReview', driver=None, isExit=False):
        self.driver = driver
        self.isExit = isExit
        self.node = node
        user = 'financeC' if node == 'preliminaryReview' else 'financeF'
        if not self.driver:
            self.login = LoginDepend('fscHost', user)
            self.driver = self.login.driver
        else:
            self.driver.get(config.urlDict.url.fscHost)
        self.boeNum = boeNum
        self._handleTimer = HandleTimer(self.driver)
        self._fscIndexPage = FscIndexPage(self.driver)
        self._myAuditListPage = MyAuditListPage(self.driver)
        self._auditAdjustDirectorPage = AuditAdjustDirectorPage(self.driver)
        self._boeCommon = BoeCommon(self.driver)
        self._ecsMyApprovalPage = EcsMyApprovalPage(self.driver)
        self._boeCommon.refresh()
        time.sleep(random.random())

    def __exit__(self, *args):
        if super().__exit__(*args):
            if self.isExit:
                self.exit()
        else:
            self.exit()

    def exit(self):
        self.driver.quit()

    # 初审同意
    def sharingCenterApproveChuShen(self, modify=False, **kwargs):
        self._handleTimer.goToTimerPage()
        self._handleTimer.runTimer('共享中心', '共享从中台同步单据')

        self._fscIndexPage.click_item('任务调整（主任）')
        self._auditAdjustDirectorPage.input_selectBoeNum(self.boeNum)
        self._auditAdjustDirectorPage.click_selectButton()

        # 任务收回
        flag = self._auditAdjustDirectorPage.elementExistsIsOrNot(*self._auditAdjustDirectorPage.getSelectResult())
        startTime = time.time()
        while True:
            endTime = time.time()
            if flag:
                break
            elif endTime - startTime > 60 * 10:
                raise AssertionError(f'共享初审-任务调整（主任）10分钟未查询到单号为：{self.boeNum} 的单据信息')
            else:
                self._auditAdjustDirectorPage.click_selectButton()
                time.sleep(random.random())
                flag = self._auditAdjustDirectorPage.elementExistsIsOrNot(
                    *self._auditAdjustDirectorPage.getSelectResult())
        self._auditAdjustDirectorPage.click_selectResult()
        if not self._auditAdjustDirectorPage.fGroupNameIsEmpty():
            self._auditAdjustDirectorPage.click_taskTakeToBack()
            self._auditAdjustDirectorPage.click_selectResult()

        # 分配到组
        self._auditAdjustDirectorPage.choiceGroup(config.urlDict.Approval.approvalGroupC, self.boeNum)

        time.sleep(random.random())

        # 分配到人
        self._auditAdjustDirectorPage.click_selectResult()
        self._auditAdjustDirectorPage.choiceOperatorUser(config.urlDict.Approval.approvalUserC, self.boeNum)

        time.sleep(random.random())

        # 进入我的工作台操作
        self._fscIndexPage.click_item('我的工作台')
        time.sleep(random.random())
        self._myAuditListPage.input_selectBoeNum(self.boeNum)
        self._myAuditListPage.click_selectButton()

        self._myAuditListPage.getIntoBoe(self.boeNum)
        self._boeCommon.switchWindow()

        # 开票申请单，初审填写发票信息
        if modify is True:
            kwargs = munchify(kwargs)
            parameterList = tuple(kwargs.keys())
            logger.info(f'参数列表为：{parameterList}')
            if 'checkCode' in parameterList:
                self._boeCommon.input_dtosCheckCode(kwargs.checkCode)

            if 'invoiceTypeCode' in parameterList:
                self._boeCommon.input_dtosInvoiceTypeCode(kwargs.invoiceTypeCode)

            if 'invoiceNo' in parameterList:
                self._boeCommon.input_dtosInvoiceNo(kwargs.invoiceNo)

            if 'invoiceCode' in parameterList:
                self._boeCommon.input_dtosInvoiceCode(kwargs.invoiceCode)

            if 'invoiceDate' in parameterList:
                self._boeCommon.input_dtosInvoiceDate(kwargs.invoiceDate)

            if 'invoiceFee' in parameterList:
                self._boeCommon.input_dtosInvoiceFee(kwargs.invoiceFee)

            if 'invoiceTax' in parameterList:
                self._boeCommon.input_dtosInvoiceTax(kwargs.invoiceTax)

            if 'invoiceRemark' in parameterList:
                self._boeCommon.input_dtosInvoiceRemark(kwargs.invoiceRemark)

            self._boeCommon.click_saveButton()

        time.sleep(random.random())
        self._boeCommon.click_accountMessage()
        self._boeCommon.click_approveButton()

        boxText = self._boeCommon.getBoxMessage2()
        # if '成功' not in boxText:
        #     logger.info(f'弹窗信息为：{boxText}')
        #     raise ZTCCLOUDError('审批不成功')
        # else:
        #     logger.info(f'弹窗信息为：{boxText}')
        #     logger.info('单据财务初审审批成功')

        self._boeCommon.switchWindow()
        return boxText

    # 复审同意
    def sharingCenterApproveFuShen(self):

        self._fscIndexPage.click_item('任务调整（主任）')
        self._auditAdjustDirectorPage.input_selectBoeNum(self.boeNum)
        self._auditAdjustDirectorPage.click_selectButton()

        flag = self._auditAdjustDirectorPage.elementExistsIsOrNot(*self._auditAdjustDirectorPage.getSelectResult())
        startTime = time.time()
        while True:
            endTime = time.time()
            if flag:
                break
            elif endTime - startTime > 60 * 15:
                raise AssertionError(f'复审节点，15分钟单据未进入共享中心，单号：{self.boeNum}')
            else:
                self._handleTimer.goToTimerPage()
                self._handleTimer.runTimer('共享中心', '生成任务')
                time.sleep(random.random())
                self._auditAdjustDirectorPage.input_selectBoeNum(self.boeNum)
                self._auditAdjustDirectorPage.click_selectButton()
                flag = self._auditAdjustDirectorPage.elementExistsIsOrNot(
                    *self._auditAdjustDirectorPage.getSelectResult())

        self._auditAdjustDirectorPage.click_selectResult()
        if not self._auditAdjustDirectorPage.fGroupNameIsEmpty():
            self._auditAdjustDirectorPage.click_taskTakeToBack()
            self._auditAdjustDirectorPage.click_selectResult()

        # 分配到组
        self._auditAdjustDirectorPage.choiceGroup(config.urlDict.Approval.approvalGroupF, self.boeNum)

        time.sleep(random.random())

        # 分配到人
        self._auditAdjustDirectorPage.click_selectResult()
        self._auditAdjustDirectorPage.choiceOperatorUser(config.urlDict.Approval.approvalUserF, self.boeNum)

        time.sleep(random.random())

        # 进入我的工作台操作
        self._fscIndexPage.click_item('我的工作台')
        self._myAuditListPage.input_selectBoeNum(self.boeNum)
        self._myAuditListPage.click_selectButton()

        self._myAuditListPage.getIntoBoe(self.boeNum)
        self._boeCommon.switchWindow()
        time.sleep(random.random())
        self._boeCommon.click_accountMessage()
        self._boeCommon.click_approveButton()
        boxText = self._boeCommon.getBoxMessage2()

        self._boeCommon.switchWindow()
        return boxText

    # 初审驳回
    def sharingCenterApproveChuShenReject(self, nodeName, text, isSendToMe=False):
        self._fscIndexPage.click_item('任务调整（主任）')
        self._handleTimer.goToTimerPage()
        self._handleTimer.runTimer('共享中心', '共享从中台同步单据')
        self._auditAdjustDirectorPage.input_selectBoeNum(self.boeNum)
        self._auditAdjustDirectorPage.click_selectButton()

        # 任务收回
        flag = self._auditAdjustDirectorPage.elementExistsIsOrNot(*self._auditAdjustDirectorPage.getSelectResult())
        startTime = time.time()
        while True:
            endTime = time.time()
            if flag:
                break
            elif endTime - startTime > 60 * 10:
                raise AssertionError(f'共享初审-任务调整（主任）10分钟未查询到单号为：{self.boeNum} 的单据信息')
            else:
                self._auditAdjustDirectorPage.click_selectButton()
                time.sleep(random.random())
                flag = self._auditAdjustDirectorPage.elementExistsIsOrNot(
                    *self._auditAdjustDirectorPage.getSelectResult())
        self._auditAdjustDirectorPage.click_selectResult()
        if not self._auditAdjustDirectorPage.fGroupNameIsEmpty():
            self._auditAdjustDirectorPage.click_taskTakeToBack()
            self._auditAdjustDirectorPage.click_selectResult()

        # 分配到组
        self._auditAdjustDirectorPage.choiceGroup(config.urlDict.Approval.approvalGroupC, self.boeNum)

        time.sleep(random.random())

        # 分配到人
        self._auditAdjustDirectorPage.click_selectResult()
        self._auditAdjustDirectorPage.choiceOperatorUser(config.urlDict.Approval.approvalUserC, self.boeNum)

        time.sleep(random.random())

        # 进入我的工作台操作
        self._fscIndexPage.click_item('我的工作台')
        time.sleep(random.random())
        self._myAuditListPage.input_selectBoeNum(self.boeNum)
        self._myAuditListPage.click_selectButton()

        self._myAuditListPage.getIntoBoe(self.boeNum)
        self._boeCommon.switchWindow()

        time.sleep(random.random())
        self._boeCommon.click_accountMessage()
        self._boeCommon.click_rejectReason()
        self._boeCommon.input_rejectOptions(text)
        self._boeCommon.click_approveReject()
        # self._ecsMyApprovalPage.click_boeBusinessReject()
        self._ecsMyApprovalPage.select_rejectNode(nodeName)
        if isSendToMe:
            self._ecsMyApprovalPage.select_switch()
        self._ecsMyApprovalPage.click_submit()

        boxText = self._boeCommon.getBoxMessage2()
        self._boeCommon.switchWindow()
        return boxText

    # 复审驳回
    def sharingCenterApproveFuShenReject(self, text):
        self._fscIndexPage.click_item('任务调整（主任）')
        self._auditAdjustDirectorPage.input_selectBoeNum(self.boeNum)
        self._auditAdjustDirectorPage.click_selectButton()

        flag = self._auditAdjustDirectorPage.elementExistsIsOrNot(*self._auditAdjustDirectorPage.getSelectResult())
        startTime = time.time()
        while True:
            endTime = time.time()
            if flag:
                break
            elif endTime - startTime > 60 * 15:
                raise ZTCCLOUDError(f'复审节点，15分钟单据未进入共享中心，单号：{self.boeNum}')
            else:
                self._handleTimer.goToTimerPage()
                self._handleTimer.runTimer('共享中心', '生成任务')
                time.sleep(random.random())
                self._auditAdjustDirectorPage.input_selectBoeNum(self.boeNum)
                self._auditAdjustDirectorPage.click_selectButton()
                flag = self._auditAdjustDirectorPage.elementExistsIsOrNot(
                    *self._auditAdjustDirectorPage.getSelectResult())

        self._auditAdjustDirectorPage.click_selectResult()
        if not self._auditAdjustDirectorPage.fGroupNameIsEmpty():
            self._auditAdjustDirectorPage.click_taskTakeToBack()
            self._auditAdjustDirectorPage.click_selectResult()

        # 分配到组
        self._auditAdjustDirectorPage.choiceGroup(config.urlDict.Approval.approvalGroupF, self.boeNum)

        time.sleep(random.random())

        # 分配到人
        self._auditAdjustDirectorPage.click_selectResult()
        self._auditAdjustDirectorPage.choiceOperatorUser(config.urlDict.Approval.approvalUserF, self.boeNum)

        time.sleep(random.random())

        # 进入我的工作台操作
        self._fscIndexPage.click_item('我的工作台')
        time.sleep(random.random())
        self._myAuditListPage.input_selectBoeNum(self.boeNum)
        self._myAuditListPage.click_selectButton()

        self._myAuditListPage.getIntoBoe(self.boeNum)
        self._boeCommon.switchWindow()
        time.sleep(random.random())
        self._boeCommon.click_accountMessage()
        self._boeCommon.click_rejectReason()
        self._boeCommon.input_rejectOptions(text)
        self._boeCommon.click_approveReject()
        # self._ecsMyApprovalPage.click_submit()

        boxText = self._boeCommon.getBoxMessage2()
        self._boeCommon.switchWindow()
        return boxText
